package com.mooc.lib_network.gson;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.mooc.lib_network.entity.BaseEntity;

import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

public class GsonResponseBodyConverter <T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        /**
         * {"msg":"登录成功","values":"
         * {\"dept_id\":47,\"pId\":47,\"time\":\"1645494013\",
         * \"token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI0NyIsImV4cCI6MzI5MDk4ODAyNywiaWF0IjoxNjQ1NDk0MDEzfQ.LTuu2MNpdLRoQl_dk-F4Xr27m9ssJ84ME9YJnQ7GZCs\",\"uId\":47,\"uName\":\"jyc\",\"uPwd\":\"123456\"}","statuesCode":"200","home":"http://118.195.161.134:8088/index.html"}
         * {"msg":"登录成功","statuesCode":200,
         * "home":"http://118.195.161.134:8088/index.html",
         * "values":{"uId":47,"uName":"jyc","time":"1645494942","pId":47,
         * "token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI0NyIsImV4cCI6MzI5MDk4OTg4NCwiaWF0IjoxNjQ1NDk0OTQyfQ.iWIKy3jleGAU1qd522PZbwvLwHcc4q7S872ep_6TwT8",
         * "uPwd":"123456","dept_id":47}
         * }
         * */
        // java.lang.IllegalStateException: closed
//        Log.e("ZXY","GsonResponseBodyConverter:"+value.string());
        JsonReader jsonReader = gson.newJsonReader(value.charStream());
        try {
            T result = adapter.read(jsonReader);
            if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
                throw new JsonIOException("JSON document was not fully consumed.");
            }
            return result;
        } finally {
            value.close();
        }
    }
}
